package cn.edu.tsinghua.weibo.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class ImgUpload extends HttpServlet {
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String savePath = this.getServletConfig().getServletContext().getRealPath("/");
		savePath += "uploads/";
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
		servletFileUpload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = servletFileUpload.parseRequest(request);
		} catch (FileUploadException fileUploadException) {
			return;
		}
		Iterator<FileItem> iterator = fileList.iterator();
		String rawname = "";
		String newname = "";
		String extname = "";
		while (iterator.hasNext()) {
			FileItem item = iterator.next();
			if (!item.isFormField()) {
				rawname = item.getName();
//				long size = item.getSize();
//				String type = item.getContentType();
//System.out.println(size + " " + type);
				if (rawname == null || rawname.trim().equals("")) {
					continue;
				}
				if (rawname.lastIndexOf(".") >= 0) {
					extname = rawname.substring(rawname.lastIndexOf("."));
				}
				File file = null;
				do {
					newname = Long.toString(System.nanoTime());
					file = new File(savePath + newname + extname);
				} while (file.exists());
				File saveFile = new File(savePath + newname + extname);
				try {
					item.write(saveFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("rawname", rawname);
		map.put("newname", newname+extname);
		JSONObject jsonObject = JSONObject.fromObject(map);
		response.setContentType("text/html; charset=utf-8");
		response.getWriter().print(jsonObject);
	}

}
